package com.example.booksales.core.config;

import com.alibaba.fastjson2.JSON;
import com.example.booksales.domain.Book;
import com.example.booksales.service.impl.BookService;
import com.example.booksales.util.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(tags="Redis测试(0613胡宇星)")
@RestController
@RequestMapping("/api/redis")
public class RedisController {
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private BookService bookService;

    @ApiOperation("通过Key和Value取得redis设定的数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "key", value = "key", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "value", value = "value", dataType = "String", dataTypeClass = String.class)
    })
    @GetMapping("/put")
    public AjaxResult put(String key, String value) {
        //存入，设置key,value,存入时间，时间单位
        redisCache.setCacheObject(key, value, 1, TimeUnit.HOURS);
        // 取出
        String v = (String) redisCache.getCacheObject(key);
        Map<String, Object> result = new HashMap<>();
        result.put("key", key);
        result.put("value", v);
        return AjaxResult.success(result);
    }
    @ApiOperation("传入id,查询图书信息，将图书信息放入缓存")
    @ApiImplicitParam(name = "bookid", value = "图书ID", required = true, dataType = "long", paramType = "query", dataTypeClass = Long.class)
    @GetMapping("/putObj")
    public AjaxResult putObj(@RequestParam Long bookid) {
        Book book = bookService.selectBookById(bookid);
        String jsonStr = JSON.toJSONString(book);
        redisCache.setCacheObject(String.valueOf(book.getBookid()), jsonStr,
                1, TimeUnit.HOURS);
        return AjaxResult.success(book);
    }
    @ApiOperation("传入图书id,从缓存中获取图书信息")
    @ApiImplicitParam(name = "bookid", value = "图书ID", required = true, dataType = "long", paramType = "query", dataTypeClass = Long.class)
    @GetMapping("/getObj")
    public AjaxResult getObj(@RequestParam Long bookid) {
        String v = redisCache.getCacheObject(String.valueOf(bookid));
        System.out.println(v);
        Book book = JSON.parseObject(v, Book.class);
        return AjaxResult.success(book);
    }
}
